<!-- src/views/student/exam/group/index.vue -->
<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-row :gutter="20" class="mb10">
      <el-col :span="6">
        <el-input
          v-model="queryParams.searchKey"
          placeholder="输入邀请码"
          clearable
          @keyup.enter.native="handleSearchByCode"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="handleSearchByCode"
          ></el-button>
        </el-input>
      </el-col>
      <el-col :span="6">
        <el-select v-model="queryParams.status" placeholder="申请状态" clearable @change="getList">
          <el-option label="全部" value=""></el-option>
          <el-option label="待审核" :value="0"></el-option>
          <el-option label="已通过" :value="1"></el-option>
          <el-option label="已拒绝" :value="2"></el-option>
          <el-option label="已退出" :value="3"></el-option>
        </el-select>
      </el-col>
    </el-row>

    <!-- 申请状态标签 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="我的考试组" name="joined"></el-tab-pane>
      <el-tab-pane label="申请记录" name="applications"></el-tab-pane>
    </el-tabs>

    <!-- 邀请码搜索结果 -->
    <el-dialog
      title="申请加入考试组"
      :visible.sync="inviteDialogVisible"
      width="30%"
      center
    >
      <div v-if="searchedGroup">
        <el-card :body-style="{ padding: '0px' }" shadow="hover">
          <img :src="searchedGroup.coverImage || require('@/assets/images/login-background.jpg')" class="image"/>
          <div style="padding: 14px;">
            <div class="group-title">{{ searchedGroup.name }}</div>
            <div class="group-desc">{{ searchedGroup.description || '暂无描述' }}</div>
            <div class="group-footer">
              <span class="group-owner">主要负责人: {{ searchedGroup.mainOwnerName }}</span>
              <span class="group-time">创建时间: {{ formatTime(searchedGroup.createTime) }}</span>
            </div>
          </div>
        </el-card>
        <div style="margin-top: 20px; text-align: center;">
          <el-button type="primary" @click="handleApplyJoin">申请加入</el-button>
          <el-button @click="inviteDialogVisible = false">取消</el-button>
        </div>
      </div>
      <div v-else style="text-align: center;">
        <p>未找到对应的考试组，请检查邀请码是否正确</p>
        <el-button @click="inviteDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 卡片列表 -->
    <!-- 考试组卡片列表 -->
    <div v-if="activeTab === 'joined'">
      <el-row :gutter="20">
        <el-col
          v-for="group in groupList"
          :key="group.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
        >
          <el-card
            :body-style="{ padding: '0px' }"
            class="group-card"
            :class="{ 'disabled-card': group.approveStatus !== 1 }"
            shadow="hover"
            @mouseenter.native="hoverCard = group.id"
            @mouseleave.native="hoverCard = null"
            @click.native="group.approveStatus === 1 && handleDetail(group)"
          >
            <img :src="group.coverImage || require('@/assets/images/login-background.jpg')" class="image"/>
            <div style="padding: 14px;">
              <div class="group-title">{{ group.name }}</div>
              <div class="group-desc">{{ group.description || '暂无描述' }}</div>
              <div class="group-footer">
                <span class="group-time">加入时间: {{ formatTime(group.joinTime) }}</span>
                <el-tag
                  v-if="group.approveStatus !== 1"
                  :type="getStatusTagType(group.approveStatus)"
                  size="mini"
                  class="status-tag"
                >
                  {{ getStatusText(group.approveStatus) }}
                </el-tag>
              </div>

              <!-- 操作按钮 -->
              <div v-show="hoverCard === group.id" class="group-actions">
                <el-button
                  v-if="group.approveStatus === 1"
                  type="text"
                  @click.stop="handleQuit(group)"
                >
                  退出
                </el-button>
                <el-button
                  v-else-if="group.approveStatus === 0"
                  type="text"
                  @click.stop="handleCancelApplication(group)"
                >
                  取消申请
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 申请记录表格 -->
    <div v-else>
      <el-table :data="applicationList" style="width: 100%">
        <el-table-column prop="groupName" label="考试组名称" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.groupName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="mainOwnerName" label="主要负责人" width="120"></el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="approveStatus" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.approveStatus)">
              {{ getStatusText(scope.row.approveStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.approveStatus === 0"
              type="text"
              @click="handleCancelApplicationByMemberId(scope.row)"
            >取消申请</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="applicationTotal > 0"
        :total="applicationTotal"
        :page.sync="applicationQuery.pageNum"
        :limit.sync="applicationQuery.pageSize"
        @pagination="getApplicationList"
      />
    </div>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  getStudentGroups,
  quitGroupOfStu,
  searchGroupByCode,
  studentJoinGroup,
  getStudentApplications,
  cancelApplication,
  cancelApplicationByMemberId
} from '@/api/exam/group'
import { parseTime } from "@/utils/quiz"

export default {
  name: 'StudentExamGroup',
  data() {
    return {
      activeTab: 'joined',
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        searchKey: '',
        status: 1 // 默认只显示已通过的
      },
      applicationQuery: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      applicationTotal: 0,
      groupList: [],
      applicationList: [],
      hoverCard: null,
      inviteDialogVisible: false,
      searchedGroup: null
    }
  },
  created() {
    this.getList()
    this.getApplicationList()
  },
  methods: {
    getList() {
      getStudentGroups(this.queryParams).then(response => {
        this.groupList = response.rows
        this.total = response.total
      })
    },

    getApplicationList() {
      getStudentApplications(this.applicationQuery).then(response => {
        this.applicationList = response.rows
        this.applicationTotal = response.total
      })
    },
    handleTabClick(tab) {
      if (tab.name === 'joined') {
        this.getList()
      } else {
        this.getApplicationList()
      }
    },

    handleSearchByCode() {
      if (!this.queryParams.searchKey) {
        this.$message.warning('请输入邀请码')
        return
      }

      searchGroupByCode(this.queryParams.searchKey).then(response => {
        this.searchedGroup = response.data
        this.inviteDialogVisible = true
      }).catch(() => {
        this.searchedGroup = null
        this.inviteDialogVisible = true
      })
    },

    handleApplyJoin() {
      if (!this.searchedGroup) return

      studentJoinGroup({
        groupId: this.searchedGroup.id,
        inviteCode: this.queryParams.searchKey
      }).then(() => {
        this.$message.success('申请已提交，等待审核')
        this.inviteDialogVisible = false
        this.queryParams.searchKey = ''
        this.getApplicationList() // 刷新申请列表
      })
    },

    handleCancelApplication(group) {
      console.log('cancel',group)
      this.$confirm('确定要取消该申请吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelApplication(group.id).then(() => {
          this.$message.success('取消申请成功')
          this.getList()
        })
      })
    },
    handleCancelApplicationByMemberId(group) {
      console.log('cancel',group)
      this.$confirm('确定要取消该申请吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelApplicationByMemberId(group.id).then(() => {
          this.$message.success('取消申请成功')
          this.getApplicationList()
        })
      })
    },

    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝',
        3: '已退出'
      }
      return statusMap[status] || '未知状态'
    },

    getStatusTagType(status) {
      const typeMap = {
        0: 'warning',
        1: 'success',
        2: 'danger',
        3: 'info'
      }
      return typeMap[status] || ''
    },

    handleDetail(group) {
      // this.$router.push(`/exam/student/group/detail/${group.id}`)
      this.$router.push({
        name: 'StudentExam',
        params: { groupId: group.id }
      })
    },

    handleQuit(group) {
      this.$confirm('确定要退出该考试组吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        quitGroupOfStu(group.id).then(() => {
          this.$message.success('退出成功')
          this.getList()
        })
      })
    },

    formatTime(time) {
      return parseTime(time, '{y}-{m}-{d}')
    }
  }
}
</script>

<style scoped>
.group-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  position: relative;
  cursor: pointer;
}

.group-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image {
  width: 100%;
  height: 160px;
  object-fit: cover;
  display: block;
}

.group-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.group-desc {
  font-size: 12px;
  color: #999;
  height: 36px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.group-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 12px;
  color: #666;
}

.group-actions {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.9);
  padding: 5px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 添加新的样式 */
.group-owner {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.group-footer {
  margin-top: 10px;
  font-size: 12px;
  color: #666;
  display: flex;
  flex-direction: column;
}
/* 表格样式 */
.el-table {
  margin-top: 20px;
}

.status-tag {
  margin-right: 10px;
}

.disabled-card {
  opacity: 0.7;
  cursor: not-allowed;
}

.disabled-card:hover {
  transform: none;
  box-shadow: none;
}

.status-tag {
  margin-left: 8px;
}
</style>
